package ui.create_group

import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.painter.BitmapPainter
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.input.pointer.onPointerEvent
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import model.vo.FriendsMappingItem
import theme.EasyChatTheme
import ui.compose.NetworkImage
import ui.home.HomeViewModel


/**
 * @author wei kunJie
 * @date 2024/4/24 15:01:18
 */
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun CreateGroupDialog(
    easyChatTheme: MutableState<EasyChatTheme>,
    homeViewModel: HomeViewModel
) {
    //rememberCoroutineScope() 是一个用于在 Composable 函数中创建协程作用域
    val coroutineScope = rememberCoroutineScope()
    //创建ViewModel
    val viewModel = remember { CreateGroupViewModel(coroutineScope) }
    viewModel.friendList.addAll(homeViewModel.friendsMappingItems)//初始化好友列表
    Dialog(
        onDismissRequest = {
            homeViewModel.createGroupDialog.value = false
        },
        properties = DialogProperties(
            dismissOnBackPress = true,
            dismissOnClickOutside = false
        )
    ) {
        if (!viewModel.isShow.value) {
            homeViewModel.createGroupDialog.value = false
        }
        val windowsCorner = 3.dp//窗口圆角大小
        Surface(
            modifier = Modifier.size(550.dp)
                .padding(5.dp)
                .shadow(3.dp, RoundedCornerShape(windowsCorner + 3.dp)),//窗口阴影样式
            color = easyChatTheme.value.mainWhite,
            shape = RoundedCornerShape(windowsCorner) //窗口圆角
        ) {
            Row(modifier = Modifier.fillMaxSize()) {
                //好友列表
                // 焦点
                val hasFocus = remember { mutableStateOf(false) }
                //左列表
                Column(modifier = Modifier.weight(1f).padding(horizontal = 18.dp, vertical = 24.dp)) {
                    Row {
                        Spacer(Modifier.width(5.dp))
                        BasicTextField(
                            value = viewModel.searchKeyWord.value,
                            onValueChange = {
                                viewModel.searchKeyWord.value = it
                            },
                            modifier = Modifier
                                .background(
                                    color = Color(0X11363636),
                                    shape = RoundedCornerShape(4.dp)
                                )
                                .height(30.dp)
                                .fillMaxWidth()
                                .border(
                                    border = if (hasFocus.value)
                                        BorderStroke(0.8.dp, easyChatTheme.value.mainColor)
                                    else BorderStroke(0.dp, Color.Transparent),
                                    shape = RoundedCornerShape(4.dp)
                                )
                                .onFocusChanged {
                                    hasFocus.value = it.hasFocus
                                },
                            singleLine = true,
                            cursorBrush = SolidColor(easyChatTheme.value.mainColor),//游标颜色
                            decorationBox = @Composable { innerTextField ->
                                Row(
                                    verticalAlignment = Alignment.CenterVertically,
                                    modifier = Modifier.padding(start = 8.dp)
                                ) {
                                    //左边的放大镜图标
                                    Icon(
                                        painter = painterResource("icon/ic_search.svg"),
                                        contentDescription = "搜索",
                                        tint = Color(0XFF696969),
                                        modifier = Modifier.size(18.dp)
                                    )
                                    //输入框
                                    Box(
                                        modifier = Modifier.weight(1f).fillMaxHeight().padding(horizontal = 3.dp),
                                        contentAlignment = Alignment.CenterStart
                                    ) {
                                        innerTextField()//输入区
                                        //hint
                                        if (viewModel.searchKeyWord.value.isEmpty()) {
                                            Text(
                                                text = "搜索", style = TextStyle(
                                                    fontSize = 12.sp,
                                                    color = Color(0XEE696969)
                                                )
                                            )
                                        }
                                    }
                                }
                            }
                        )
                        Spacer(Modifier.width(5.dp))
                    }
                    val isActivityVerticalScrollbar = remember { mutableStateOf(false) }
                    Box(modifier = Modifier
                        .weight(1f)
                        .padding(top = 10.dp)
                        .onPointerEvent(PointerEventType.Enter) { isActivityVerticalScrollbar.value = true }
                        .onPointerEvent(PointerEventType.Exit) { isActivityVerticalScrollbar.value = false }) {
                        val state = rememberLazyListState()
                        //渲染列表
                        LazyColumn(modifier = Modifier.fillMaxSize(), state = state) {
                            items(viewModel.friendList) { item ->
                                if (viewModel.searchKeyWord.value == "") {
                                    FriendSelectRow(easyChatTheme, true, item, viewModel)
                                } else if (
                                    item.userName.contains(viewModel.searchKeyWord.value) ||
                                    item.account.contains(viewModel.searchKeyWord.value)
                                ) {
                                    FriendSelectRow(easyChatTheme, true, item, viewModel)
                                }
                                Spacer(Modifier.height(1.dp))
                            }
                        }
                        //只有当鼠标进入时才出现滚动条
                        if (isActivityVerticalScrollbar.value) {
                            VerticalScrollbar(
                                modifier = Modifier.align(Alignment.CenterEnd).fillMaxHeight(),
                                adapter = rememberScrollbarAdapter(
                                    scrollState = state
                                )
                            )
                        }
                    }
                }
                Spacer(modifier = Modifier.width(1.dp).fillMaxHeight().background(color = Color(0x22747A80)))
                //选中的好友
                Column(modifier = Modifier.weight(1f).padding(horizontal = 18.dp, vertical = 24.dp)) {
                    Row {
                        Spacer(Modifier.width(7.dp))
                        Text(text = "创建群聊", fontSize = 14.sp)
                        Spacer(modifier = Modifier.weight(1f))
                        Text(
                            text = "已选${viewModel.choseFriendList.size}个联系人",
                            fontSize = 13.sp,
                            color = Color(0xFF8a8a8a)
                        )
                        Spacer(Modifier.width(5.dp))
                    }
                    val isActivityVerticalScrollbar = remember { mutableStateOf(false) }
                    Box(modifier = Modifier
                        .padding(top = 10.dp)
                        .weight(1f)
                        .onPointerEvent(PointerEventType.Enter) { isActivityVerticalScrollbar.value = true }
                        .onPointerEvent(PointerEventType.Exit) { isActivityVerticalScrollbar.value = false }) {
                        val state = rememberLazyListState()
                        //渲染列表
                        LazyColumn(modifier = Modifier.fillMaxSize(), state = state) {
                            items(viewModel.choseFriendList) { item ->
                                FriendSelectRow(easyChatTheme, false, item, viewModel)
                                Spacer(Modifier.height(1.dp))
                            }
                        }
                        //只有当鼠标进入时才出现滚动条
                        if (isActivityVerticalScrollbar.value) {
                            VerticalScrollbar(
                                modifier = Modifier.align(Alignment.CenterEnd).fillMaxHeight(),
                                adapter = rememberScrollbarAdapter(
                                    scrollState = state
                                )
                            )
                        }
                    }
                    Row {
                        Spacer(modifier = Modifier.weight(1f))
                        Button(
                            enabled = viewModel.choseFriendList.size != 0 && viewModel.createClickEnable.value,
                            onClick = {
                                //创建群聊
                                viewModel.createGroup(homeViewModel)
                            }, colors = ButtonDefaults.buttonColors(
                                backgroundColor = easyChatTheme.value.mainColor,
                            )
                        ) {
                            Text(text = "确定")
                        }
                        Spacer(modifier = Modifier.width(10.dp))
                        Button(
                            onClick = {
                                homeViewModel.createGroupDialog.value = false
                            }, colors = ButtonDefaults.buttonColors(
                                backgroundColor = Color(0xFFF5FAFF),
                            )
                        ) {
                            Text(text = "取消")
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun FriendSelectRow(
    easyChatTheme: MutableState<EasyChatTheme>,
    isLeft: Boolean,
    friendsMappingItem: FriendsMappingItem,
    viewModel: CreateGroupViewModel
) {
    Surface(
        modifier = Modifier.fillMaxWidth(),
        color = Color.Transparent,
        shape = RoundedCornerShape(5.dp) //窗口圆角
    ) {
        Row(verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier.clickable(
                onClick = {
                    if (isLeft) {
                        if (viewModel.choseFriendMap.containsKey(friendsMappingItem.account)) {//取消选中
                            viewModel.choseFriendMap.remove(friendsMappingItem.account)
                            viewModel.choseFriendList.remove(friendsMappingItem)
                        } else {//选中
                            viewModel.choseFriendMap[friendsMappingItem.account] = friendsMappingItem
                            viewModel.choseFriendList.add(friendsMappingItem)
                        }
                    } else {//取消选中
                        viewModel.choseFriendMap.remove(friendsMappingItem.account)
                        viewModel.choseFriendList.remove(friendsMappingItem)
                    }
                }
            ).padding(vertical = 5.dp).clip(RoundedCornerShape(5.dp))) {
            if (isLeft)
                Spacer(Modifier.width(10.dp))
            if (isLeft) {
                if (viewModel.choseFriendMap.containsKey(friendsMappingItem.account)) {
                    Icon(
                        painter = painterResource("icon/ic_chose.svg"),
                        contentDescription = "选中",
                        modifier = Modifier.size(17.dp),
                        tint = easyChatTheme.value.mainColor
                    )
                } else {
                    Icon(
                        painter = painterResource("icon/ic_unchose.svg"),
                        contentDescription = "未选中",
                        modifier = Modifier.size(17.dp),
                        tint = Color(0xFF8a8a8a)
                    )
                }
            }
            if (isLeft)
                Spacer(modifier = Modifier.width(10.dp))
            else Spacer(modifier = Modifier.width(8.dp))
            //头像
            NetworkImage(
                url = friendsMappingItem.headUrl,
                painterFor = { remember { BitmapPainter(it) } },
                contentDescription = "头像",
                modifier = Modifier.size(40.dp).clip(CircleShape),
                contentScale = ContentScale.Crop,
                defaultPainterFor = painterResource("image/default_head.png")
            )
            Spacer(modifier = Modifier.width(10.dp))
            Text(text = friendsMappingItem.userName, modifier = Modifier.weight(1f))
            if (!isLeft) {
                Icon(
                    painter = painterResource("icon/ic_delete2.svg"),
                    contentDescription = "删除",
                    tint = Color(0xFF8a8a8a),
                    modifier = Modifier.size(17.dp)
                )
                Spacer(Modifier.width(10.dp))
            }
        }
    }
}